<template>
  <div class="shop">
    <h1 class="section-title">购车商城</h1>

    <!-- 搜索控件 -->
    <div class="navbar">
      <div class="search-container">
        <div class="search-bar">
          <input type="text" v-model="searchText" placeholder="搜索车型..." @keyup.enter="handleSearch">
          <button @click="handleSearch">搜索</button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <div class="filter-section">

      <!-- 车型类别筛选 -->
      <div class="filter-group">
        <label>车型类别</label>
        <div class="category-tags">
          <span @click="toggleType(null)" :class="{ active: !selectedType }">
            全部
          </span>
          <span v-for="type in uniqueTypes" :key="type" @click="toggleType(type)"
            :class="{ active: selectedType === type }">
            {{ type }}
          </span>
        </div>
      </div>

      <!-- 能源类型筛选 -->
      <div class="filter-group">
        <label>能源类型</label>
        <div class="category-tags">
          <span @click="toggleEnergy(null)" :class="{ active: !selectedEnergy }">
            全部
          </span>
          <span v-for="energy in uniqueEnergies" :key="energy" @click="toggleEnergy(energy)"
            :class="{ active: selectedEnergy === energy }">
            {{ energy }}
          </span>
        </div>
          <label>品牌筛选</label>
      <div class="category-tags">
        <span @click="toggleBrand(null, '')" :class="{ active: !selectedBrandId }">
          全部
        </span>
        <span v-for="brand in brands" :key="brand.id" @click="toggleBrand(brand.brandId, brand.brandName)"
          :class="{ active: selectedBrandId === brand.brandId }">
          {{ brand.brandName }}
        </span>
      </div>
      </div>

    

    <div class="filter-group">
    
    </div>
  
</div>
  <div class="car-grid">
    <div class="car-card" v-for="car in filteredCars" :key="car.id" @click="showCarDetail(car)">
      <div class="car-image">
        <img :src="car.image" :alt="car.name">
        <div class="badge" v-if="car.isNew">新款</div>
      </div>
      <div class="car-info">
        <h3>{{ car.name }}</h3>
        <p class="price">{{ car.price }}</p>
        <div class="specs">
          <span>{{ car.modelTypeName }} · {{ car.modelEnergy }}</span>
        </div>
        <button class="quick-view" @click="$router.push({ name: 'config', params: { modelId: car.id } })">快速查看</button>
      </div>
    </div>
  </div>
</div>
  <div class="pagination" v-if="filteredCars.length > 0">
    <button v-for="page in totalPages" :key="page" @click="currentPage = page"
      :class="{ active: currentPage === page }">
      {{ page }}
    </button>
  </div>

  <div class="no-results" v-if="cars.length === 0">
    <p>没有找到符合条件的车型</p>
    <button @click="resetFilters">重置筛选条件</button>
  </div>

</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import api from '@/api/index';

const router = useRouter();
const route = useRoute();

const itemsPerPage = 8;

// 响应式状态
const cars = ref([]); // 清空静态数据，改为从API获取
const loading = ref(false); // 添加加载状态

const categories = ref();

// 初始化空的品牌数组
const brands = ref([]);

// 调用API获取所有汽车品牌
const fetchCarBrands = async () => {
  try {
    const response = await api.getCarBrands();
    console.log('获取到的品牌数据:', response.data);
    // 假设API返回的数据格式为[{id: 'benz', name: '奔驰'}, ...]
    brands.value = response.data.result;
  } catch (error) {
    console.error('获取品牌数据失败:', error);

  }
};

// 调用API获取车辆数据
const fetchCars = async (modelDTO = {}) => {
  try {
    loading.value = true;
    // 确保车型数据已加载
    if (!categories.value || !Array.isArray(categories.value) || categories.value.length === 0) {
      console.log('车型数据未加载，先获取车型数据...');
      await fetchModelType();
    }
    const response = await api.searchCarsByDTO(modelDTO);
    console.log('获取到的车辆数据:', response.data);

    if (response.data && Array.isArray(response.data.result)) {
      // 假设API返回的数据格式需要转换以匹配现有组件期望的格式
      cars.value = response.data.result.map(car => {
        // 查找对应的车型数据 - 添加categories.value存在性检查
       
        const category = (categories.value && Array.isArray(categories.value))
          ? categories.value.find(cat => cat.modelTypeId === Number(car.modelTypeId)) || {} 
          : {};

        return {
          id: car.modelId,
          brandId: car.brandId,
          name: `${car.modelName} ${car.modelVersion}`,
          price: `¥${car.modelPrice.toLocaleString()}起`,
          modelTypeName: category.modelTypeName || '未知',
          modelEnergy: category.modelEnergy || '未知',
          image: car.picUrl,
          category: 'sedan',
          isNew: car.year === '2025',
          priceValue: car.modelPrice
        };
       
      });
    }
    else {
      cars.value = [];
    }
  } catch (error) {
    console.error('获取车辆数据失败:', error);
    cars.value = [];
  } finally {
    loading.value = false;
  }
};

//#region 车型筛选逻辑（车型类别和能源类型）
// 调用api获取车型数据
const fetchModelType = async () => {
  try {
    loading.value = true;
    const response = await api.getAllModelType();
    categories.value = response.data && Array.isArray(response.data.result) ? response.data.result : [];
    console.log('获取到的车型数据:', categories.value);
    // 添加车型ID日志，方便调试
    console.log('车型ID列表:', categories.value.map(cat => cat.modelTypeId));
  } catch (error) {
    console.error('获取车型数据失败:', error);
    categories.value = [];
  } finally {
    loading.value = false;
  }
};

// 去重后的车型类别
const uniqueTypes = computed(() => {
  return categories.value ? [...new Set(categories.value.map(item => item.modelTypeName))] : [];
});

// 去重后的能源类型
const uniqueEnergies = computed(() => {
  return categories.value ? [...new Set(categories.value.map(item => item.modelEnergy))] : [];
});

// 选中的车型和能源
const selectedType = ref(null);
const selectedEnergy = ref(null);

// 在已有的响应式变量中添加
const selectedModelTypeId = ref(null);

// 修改组合筛选逻辑
const filteredCategories = computed(() => {
  // 先重置modelTypeId
  selectedModelTypeId.value = null;

  // 如果没有选择任何筛选条件，返回空数组
  if (!selectedType.value && !selectedEnergy.value) {
    console.log('没有选择车型或能源，返回空数组');
    return [];
  }

  const filtered = categories.value.filter(item => {
    const typeMatch = selectedType.value ? item.modelTypeName === selectedType.value : true;
    const energyMatch = selectedEnergy.value ? item.modelEnergy === selectedEnergy.value : true;
    return typeMatch && energyMatch;
  });

  console.log('筛选结果数量:', filtered.length);
  console.log('筛选结果:', filtered);

  // 只要有筛选结果，就设置modelTypeId（取第一个结果的modelTypeId）
  if (filtered.length > 0) {
    selectedModelTypeId.value = String(filtered[0].modelTypeId);
    console.log('设置modelTypeId:', selectedModelTypeId.value);
  }

  return filtered;
});

//#endregion

//#region 搜索框筛选事件
// 搜索框相关
const searchText = ref('');

// 搜索事件处理
const handleSearch = () => {
  currentPage.value = 1; // 重置分页到第一页
  fetchFilteredCars();
};
//#endregion

// 根据筛选条件构建DTO并调用API
const fetchFilteredCars = () => {
  // 引用filteredCategories以确保它被计算
  const _ = filteredCategories.value;
  // 构建查询条件
  const modelDTO = {};

  if (selectedBrandId.value !== null) {
    modelDTO.brandId = selectedBrandId.value;
  }

  if (selectedModelTypeId.value !== null) {
    modelDTO.modelTypeId = selectedModelTypeId.value;
  }

  // 添加搜索文本条件
  if (searchText.value.trim()) {
    modelDTO.modelName = searchText.value.trim();
  }

  console.log('查询条件:', modelDTO);
  fetchCars(modelDTO);
};


// 在组件挂载时调用获取数据的方法
onMounted(async () => {
  await fetchCarBrands();
  await fetchModelType();
  await fetchCars({});
});

//#region 点击事件处理
const toggleType = (type) => {
  selectedType.value = type;
  currentPage.value = 1; // 重置分页到第一页
  fetchFilteredCars();   // 触发数据更新
};

const toggleEnergy = (energy) => {
  selectedEnergy.value = energy;
  currentPage.value = 1; // 重置分页到第一页
  fetchFilteredCars();   // 触发数据更新
};

const resetFilters = () => {
  selectedBrandId.value = null;
  selectedBrandName.value = '';
  selectedType.value = null;
  selectedEnergy.value = null;
  searchText.value = ''; // 重置搜索框
  currentPage.value = 1;
  fetchCars();
};

const toggleBrand = (brandId, brandName) => {
  if (selectedBrandId.value === brandId) {
    selectedBrandId.value = null;
    selectedBrandName.value = '';
  } else {
    selectedBrandId.value = brandId;
    selectedBrandName.value = brandName;
  }
  currentPage.value = 1; // 重置分页到第一页
  fetchFilteredCars();
};
//#endregion

const selectedBrandId = ref(null);
const selectedBrandName = ref('');

const currentPage = ref(1);

// 计算属性：筛选并分页显示车辆数据
const filteredCars = computed(() => {
  // 首先筛选品牌
  let filtered = cars.value.filter(car => {
    const inBrand = !selectedBrandId.value || car.brandId === Number(selectedBrandId.value);
    return inBrand;
  });

  

  // 然后进行分页
  const start = (currentPage.value - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  const paginated = filtered.slice(start, end);

  console.log('分页后显示的车辆数量:', paginated.length);
  return paginated;
});

const totalPages = computed(() => {
  const filtered = cars.value.filter(car => {
    const inBrand = !selectedBrandId.value || car.brandId === Number(selectedBrandId.value);
    return inBrand;
  });
  return Math.ceil(filtered.length / itemsPerPage);
});

const showCarDetail = (car) => {
  router.push({ name: 'config', params: { modelId: car.id } });
};
</script>

<style scoped>
.shop-container {
  padding: 3rem 2rem;
  max-width: 1400px;
  margin: 0 auto;
}

.section-title {
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  text-align: center;
  color: #c0c0c0;
  font-weight: 250;
  letter-spacing: 0.05em;
}

/* 导航栏样式 */
.navbar {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem;
  background-color: #0a0a0a;
}

.search-bar {
  display: flex;
  border: 1px solid #666;
  border-radius: 6px;
  overflow: hidden;
  width: 500px;
}

.search-bar input {
  border: none;
  padding: 0.5rem;
  flex: 1;
  background-color: #f5f5f5;
  font-size: 0.9rem;
}

.search-bar button {
  border: none;
  background-color: #282828;
  color: white;
  padding: 0.5rem 1.5rem;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 0.9rem;
  white-space: nowrap;
}

.car-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 2.5rem;
}

.car-card {
  background: rgba(30, 30, 30, 0.7);
  border-radius: 4px;
  padding: 2rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.car-card:hover {
  background: rgba(40, 40, 40, 0.7);
  transform: translateY(-5px);
}

.car-card h3 {
  color: #fff;
  margin-bottom: 1rem;
  font-weight: 300;
  font-size: 1.5rem;
}

.car-card p {
  color: #aaa;
  line-height: 1.8;
  font-weight: 300;
}

.shop {
  max-width: 1200px;
  margin: 0 auto;
  padding: 1rem;
}


.filter-section {
  background-color: #3a3a3a;
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;
}

.filter-group {
  margin-bottom: 1.5rem;
}

.filter-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
  color: #ffffff;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.category-tags span {
  padding: 0.5rem 1rem;
  background-color: #505050;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.category-tags span:hover {
  background-color: #ddd;
}

.category-tags span.active {
  background-color: #000000;
  color: white;
}

.car-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.car-card {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}

.car-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.car-image {
  position: relative;
  height: 180px;
}

.car-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ce2c1a;
  color: white;
  padding: 0.3rem 0.6rem;
  border-radius: 4px;
  font-size: 0.8rem;
}

.car-info {
  padding: 1.2rem;
}

.car-info h3 {
  margin-bottom: 0.5rem;
  font-size: 1.1rem;
}

.price {
  color: #e74c3c;
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.specs {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 1rem;
}

.quick-view {
  width: 100%;
  padding: 0.6rem;
  background-color: #ffffff;
  color: rgb(0, 0, 0);
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s ease;


}

.quick-view:hover {
  background-color: #000000;
  color: rgb(255, 255, 255)
}

.pagination {
  display: flex;
  justify-content: center;
  gap: 0.5rem;
  margin-top: 2rem;
}

.pagination button {
  width: 40px;
  height: 40px;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.pagination button:hover {
  background-color: #f5f5f5;
}

.pagination button.active {
  background-color: #000000;
  color: white;
  border-color: #ffffff;
}

.no-results {
  text-align: center;
  padding: 3rem 0;
}

.no-results p {
  font-size: 1.2rem;
  color: #666;
  margin-bottom: 1rem;
}

.no-results button {
  padding: 0.8rem 1.5rem;
  background-color: #ffffff;
  color: rgb(0, 0, 0);
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.no-results button:hover {
  background-color: #000000;
  color: rgb(255, 255, 255);
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-overlay p {
  color: white;
  margin-top: 1rem;
}
</style>